﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class WebUserControl : System.Web.UI.UserControl
{
    string str = BCDataCenter.Configuration.CurrentConnectionString;
    DataSet ds;
    SqlConnection con;
    SqlCommand checkTable, DeleteData, InsertData, UpdateData;
    SqlTransaction tran;
    MethodClassCommon common;
    static string ngaychot = null;
    string IRAyear = "IRA" + System.DateTime.Now.Year.ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                MultiView1.ActiveViewIndex = 0;
                common = new MethodClassCommon();
                string ClosedDate = common.GetDataDepend("get_CloseDate", "Sitecode", Session["Sitecode"].ToString());
                DateTime dateTest;
                System.Globalization.DateTimeFormatInfo sFormat = new System.Globalization.DateTimeFormatInfo();
                sFormat.ShortDatePattern = "dd/MM/yyyy";
                dateTest = Convert.ToDateTime(ClosedDate, sFormat);
                TextBox1.Text = dateTest.Date.AddDays(1).ToString("dd/MM/yyyy");
                ngaychot = TextBox1.Text;
                this.SqlDataSource1.ConnectionString = str;
                this.SqlDataSource1.SelectParameters["sitecode"].DefaultValue = Session["Sitecode"].ToString();
            }
            Session["iradate"] = TextBox1.Text;
            Session["table"] = IRAyear;
            Session["location"] = DropDownList1.SelectedValue.ToString();
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        con = new SqlConnection(str);
        con.Open();
        SqlDataReader dr;
        SqlCommand command = new SqlCommand("CHECK_HOADON_NGHIEPVU_KHO", con);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@Closedate", TextBox1.Text));
        command.Parameters.Add(new SqlParameter("@sitecode", Session["Sitecode"].ToString()));
        dr = command.ExecuteReader(CommandBehavior.CloseConnection);
        int i = 0;
        while (dr.Read())
        {
            if (dr[1] != null)
            {
                if (dr[1].ToString() == "I")
                {
                    uscMsgBox1.AddMessage("Còn hóa đơn chưa chốt", uscMsgBox.enmMessageType.Error);

                    i = 1;
                    break;
                }
                else
                {
                    uscMsgBox1.AddMessage("Còn nghiệp vụ kho chưa chốt", uscMsgBox.enmMessageType.Error);

                    i = 2;
                    break;
                }
            }
        }
        dr.Close();
        if (i == 0)
        {
            try
            {
                SqlDataAdapter da = new SqlDataAdapter("GET_MAHANG_abckeyA", con);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                ds=new DataSet();
                da.Fill(ds);
                this.GridView1.DataSource = ds.Tables[0];
                this.GridView1.DataBind();
            }
            catch (Exception ex)
            {
                BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
                string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                obj.ErrorLog(ex.Message, method);
            }
        }


    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        if (this.GridView1.Rows.Count>0)
        {
          
            con = new SqlConnection(str);
            con.Open();
            tran = con.BeginTransaction();
            checkTable = new SqlCommand();
            checkTable.Connection = con;
            DeleteData = new SqlCommand();
            DeleteData.Connection = con;
            InsertData = new SqlCommand();
            InsertData.Connection = con;
            UpdateData = new SqlCommand();
            UpdateData.Connection = con;
          
            try
            {
                //kiem tra table co ton tai
                checkTable.CommandText = "CHECK_TABLE";
                checkTable.CommandType = CommandType.StoredProcedure;
                checkTable.Parameters.Add(new SqlParameter("@TableName", IRAyear));
                checkTable.Transaction = tran;
                checkTable.ExecuteNonQuery();

                //xoa data trong table
                DeleteData.CommandText = "DELETE FROM " + IRAyear + " WHERE location='" + DropDownList1.SelectedValue.ToString() + "' and iradate='" + TextBox1.Text.Trim() + "'";
                DeleteData.CommandType = CommandType.Text;
                DeleteData.Transaction = tran;
                DeleteData.ExecuteNonQuery();

                //insert data vao table
                string CurrentDate = System.DateTime.Now.Date.ToString("dd/MM/yyyy");
                int i = 0;
                TextBox sl;
                string a = "0";
                foreach (GridViewRow grv in GridView1.Rows)
                {
                    InsertData.Parameters.Clear();
                    sl = (TextBox)GridView1.Rows[i].FindControl("TextBox2");
                    if ((sl.Text == "") || (sl.Text == null))
                    {
                        a = "0";
                    }
                    else
                    {
                        a = sl.Text.Trim();
                    }
                    InsertData.CommandText = "INSERT_IRA_YYYY";
                    InsertData.CommandType = CommandType.StoredProcedure;
                    InsertData.Parameters.Add(new SqlParameter("@TableName", IRAyear));
                    InsertData.Parameters.Add(new SqlParameter("@itemkey", grv.Cells[1].Text));
                    InsertData.Parameters.Add(new SqlParameter("@iradate", TextBox1.Text.Trim()));
                    InsertData.Parameters.Add(new SqlParameter("@inputdate", CurrentDate));
                    InsertData.Parameters.Add(new SqlParameter("@location", DropDownList1.SelectedValue.ToString()));
                    InsertData.Parameters.Add(new SqlParameter("@chuoitinh", a + ",4"));
                    InsertData.Parameters.Add(new SqlParameter("@sitecode", Session["Sitecode"].ToString()));
                    InsertData.Transaction = tran;
                    InsertData.ExecuteNonQuery();
                    i++;
                }
              
               
                //update data vao table
                UpdateData.CommandText = "UPDATE_IRA_YYYY";
                UpdateData.CommandType = CommandType.StoredProcedure;
                UpdateData.Parameters.Add(new SqlParameter("@TableName", IRAyear));
                UpdateData.Parameters.Add(new SqlParameter("@date", TextBox1.Text.Trim()));
                UpdateData.Transaction = tran;
                UpdateData.ExecuteNonQuery();

                tran.Commit();

                
                //uscMsgBox1.AddMessage("Lưu dữ liệu thành công", uscMsgBox.enmMessageType.Success);
                MultiView1.ActiveViewIndex = 1;
            }
            catch (Exception ex)
            {
                tran.Rollback();
               
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
       
            }
            finally
            {
                con.Close();
            }
        }
        else
        {
            uscMsgBox1.AddMessage("Không có dữ liệu,xin quay lại chọn ngày khác", uscMsgBox.enmMessageType.Error);
            MultiView1.ActiveViewIndex = 0;
        }

    }
    protected void Button3_Click(object sender, EventArgs e)
    {

        Response.Redirect("reportBaoCaoDoiChieu.aspx");

    }
    protected void Button4_Click(object sender, EventArgs e)
    {
       
       
        try
        {
            DateTime dateTestngayChot;
             DateTime dateTestngayChot1;
            System.Globalization.DateTimeFormatInfo sFormatngaychot = new System.Globalization.DateTimeFormatInfo();
            sFormatngaychot.ShortDatePattern = "dd/MM/yyyy";
            dateTestngayChot = Convert.ToDateTime(TextBox1.Text, sFormatngaychot);
            sFormatngaychot.ShortDatePattern = "dd/MM/yyyy";
            dateTestngayChot1 = Convert.ToDateTime(ngaychot, sFormatngaychot);
            if ((dateTestngayChot) > (dateTestngayChot1))
            {
                uscMsgBox1.AddMessage("Chỉ được nhập IRA sau ngày khóa sổ 1 ngày", uscMsgBox.enmMessageType.Error);
                TextBox1.Text = ngaychot;
            }
            else
            {

                if ((DropDownList1.SelectedValue.ToString() == "") || (DropDownList1.SelectedValue == null))
                {
                    uscMsgBox1.AddMessage("Không có dữ liệu", uscMsgBox.enmMessageType.Error);
                }
                else
                {
                    nhan://[!!];
                    con = new SqlConnection(str);
                    con.Open();

                    SqlCommand command = new SqlCommand("select itemkey from " + IRAyear + " where iradate='" + TextBox1.Text + "' and location='" + DropDownList1.SelectedValue.ToString() + "'", con);

                    try
                    {

                        string itemkey = Convert.ToString(command.ExecuteScalar());
                        if ((itemkey == "") || (itemkey == null))
                        {
                            MultiView1.ActiveViewIndex = 2;
                        }
                        else
                        {

                            MultiView1.ActiveViewIndex = 1;
                        }
                        Session["location"] = DropDownList1.SelectedValue.ToString();
                        Session["iradate"] = TextBox1.Text;
                        Session["table"] = IRAyear;
                    }
                    catch
                    {
                        SqlCommand check = new SqlCommand("CHECK_TABLE", con);
                        check.CommandType = CommandType.StoredProcedure;
                        check.Parameters.Add(new SqlParameter("@TableName", IRAyear));
                        check.ExecuteNonQuery();
                        goto nhan;
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 0;
    }
    protected void Button6_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 0;
    }
}
